package com.y2.authprj.utils.login.Inteceptor;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.y2.authprj.bean.auth.model.StaffInfo;
import com.y2.authprj.mvc.controller.auth.FunctionauthorityController;
import com.y2.authprj.utils.login.LoginCheck;
import com.y2.authprj.utils.login.LoginCheckUntil;

public class AuthCheckInteceptor extends HandlerInterceptorAdapter{

	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	        
	        HandlerMethod methodHandler=(HandlerMethod) handler;
	        Method method = methodHandler.getMethod();
	        LoginCheck auth=method.getAnnotation(LoginCheck.class);
	        boolean flag=false;
	        //如果方法中添加了@AuthCheckAnnotation 这里的auth不为null
	        if(auth!=null){
	        	LoginCheckUntil info=new LoginCheckUntil();
	        	String authName=auth.value();
	        	int functionauthorityIdByName=0;
	        	//根据资源名称查找资源的ID
	        	if(info.findFunctionauthorityIdByName(authName)!=-1){
	        		functionauthorityIdByName=info.findFunctionauthorityIdByName(authName);
	        	}
	        	//使用session保存当前登录用户的信息
	        	StaffInfo staffInfo=(StaffInfo)request.getSession().getAttribute("findByStaffName");
	        	if(staffInfo!=null && functionauthorityIdByName!=0){
	        		List<Integer> functionauthorityIdByStaffId = info.functionauthorityIdByStaffId(staffInfo.getStaffId());
	        		if(functionauthorityIdByStaffId!=null){
	        			for(Integer id:functionauthorityIdByStaffId){
	     	        	   if(id.equals(functionauthorityIdByName)){
	     	        		  flag=true;
	     	        	   }
	     	           }
	        		}
	        	}
	        }else{
	        	flag=true;
	        }
	        if(!flag){
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}
	        
	        return flag;
	    }

}
